package com.op.teachingliteapp.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.CourseBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.teachinglite.CourseUrl;
import com.op.teachingliteapp.database.dao.CourseDao;
import com.op.teachingliteapp.fragment.SettingsFragment;
import com.op.teachingliteapp.fragment.UserInformationFragment;
import com.op.teachingliteapp.fragment.course.CourseFragment;
import com.op.teachingliteapp.fragment.smartpan.SmartPanFragment;
import com.op.teachingliteapp.service.CourseService;
import com.op.teachingliteapp.service.UserService;
import com.op.teachingliteapp.util.DirUtils;
import com.op.teachingliteapp.util.SharedPreferencesUtils;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;
import com.op.teachingliteapp.util.http.VolleySingleton;
import com.op.teachingliteapp.util.network.NetworkUtils;
import com.op.teachingliteapp.widget.RoundImageView;

public class HomeActivity extends Activity {

	private static final String TAG = HomeActivity.class.getSimpleName();
	private String getCourseUserId;
	private RelativeLayout userLoad;

	private boolean isExit = false;
	private TextView mainTitle, userName;
	private Button YunKeTangBtn; // cloudClassBtn
	private Button cloudDiskBtn; // 云盘
	private Button settingsBtn; // settingsBtn
	private Button btn_refurbish;// 刷新按钮
	private RelativeLayout informationBar;// 界面顶端的Bar

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		setupView();
		// 前一个参数是去userId的key，我之前设置的是userId本身，所以这样取,第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
		getCourseUserId = SharedPreferencesUtils.get(Common.Prefs.USER_ID, this);
		// 判断Wifi和GSM网络状况，被邱老师改过
		if (NetworkUtils.isNetworkAvailable(this)) {
			getCoursePost();
		} else {
			// 如果没有Wifi无连接 则从数据库中取课程列表
			CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
			List<CourseBean> courses = courseDao.getCoursesByUserId(getCourseUserId);

			String str = courses.size() + "\\";
			for (int i = 0; i < courses.size(); i++) {
				str += courses.get(i).getName() + "\\";
			}
			switchFragment(new CourseFragment());
			Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
		}

	}

	/*
	 * 监听刷新按钮
	 */
	public void reFlashOnClick(View v) {
		btn_refurbish.setClickable(false);
		getCoursePost();
	}

	// /*
	// * 监听更多按钮
	// */
	// public void morePopupOnClick(View v) {
	// PopupMenu popupMenu = new PopupMenu(HomeActivity.this, v);
	// popupMenu.getMenuInflater().inflate(R.menu.popup_menu_main,
	// popupMenu.getMenu());
	// popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
	//
	// @Override
	// public boolean onMenuItemClick(MenuItem item) {
	// switch (item.getItemId()) {
	// case R.id.First:
	// Toast.makeText(getBaseContext(), "功能一", Toast.LENGTH_SHORT).show();
	// break;
	// case R.id.Second:
	// Toast.makeText(getBaseContext(), "功能二", Toast.LENGTH_SHORT).show();
	// break;
	// case R.id.Third:
	// Toast.makeText(getBaseContext(), "功能三", Toast.LENGTH_SHORT).show();
	// break;
	// default:
	// break;
	// }
	// return false;
	// }
	// });
	//
	// popupMenu.show();
	// }

	private void ToQuitTheApp() {
		if (isExit) {
			// ACTION_MAIN with category CATEGORY_HOME 启动主屏幕
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			startActivity(intent);
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);// 使虚拟机停止运行并退出程序
			// finish();
		} else {
			isExit = true;
			Toast.makeText(HomeActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			mHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
		}
	}

	// 创建Handler对象，用来处理消息
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {// 处理消息
			super.handleMessage(msg);
			isExit = false;
		}
	};

	/**
	 * 用post发送ID获得课程数据
	 * 
	 * @author 陈宇瀚
	 */
	public void getCoursePost() {
		CourseService.clear(this);
		CourseService.syncCourses(new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				Log.i(TAG, response);
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e(TAG, error.getMessage(), error);
			}
		});
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Prefs.USER_ID, getCourseUserId));
		HttpPostTask task = new HttpPostTask(HomeActivity.this, CourseUrl.GET_COURSE_BY_USER_ID,
				params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
				// 清空所有课程
				CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
				courseDao.empty();
			}

			@Override
			public void completed(String result) {

				// 存储数据
				try {
					if (!StringUtils.isEmptyOrStringNull(result)) {
						JSONObject jsonObject = new JSONObject(result);
						Log.i("------------------------------",
								"dsa______________________________________________:" + result);

						JSONArray jsonArray = jsonObject.getJSONObject("resultMap").getJSONArray(
								"courseList");

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject courseObject = jsonArray.getJSONObject(i);
							CourseBean courseBean = new CourseBean();
							courseBean.fillAttributeByJson(courseObject);
							CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
							courseDao.insert(courseBean);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				getFragmentManager().findFragmentById(R.id.fragment_content).onResume();
				btn_refurbish.setClickable(true);
				// 建立相应课程的文件夹
				CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
				List<CourseBean> courses = courseDao.getCoursesByUserId(getCourseUserId);
				createFolders(getCourseUserId, courses);
			}

		});
		task.execute();
	}

	private void switchFragment(Fragment fragment) {
		getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
		getFragmentManager().beginTransaction().addToBackStack(null)
				.replace(R.id.fragment_content, fragment).commit();

	}

	@Override
	public void onBackPressed() {
		if (getFragmentManager().getBackStackEntryCount() == 1) {
			ToQuitTheApp();
			return;
		}
		super.onBackPressed();
	}

	/**
	 * 创建 相应课程的文件夹
	 * 
	 * @param userId
	 * @param list
	 */
	public void createFolders(final String userId, final List<CourseBean> list) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				DirUtils dirUtils = new DirUtils(HomeActivity.this, userId);
				List<String> courses = new ArrayList<String>();
				for (int i = 0; i < list.size(); i++) {
					// Log.i(TAG, list.get(i).getName());
					courses.add(list.get(i).getName());
				}
				dirUtils.initDirs(courses);
				// dirUtils.getFilesNameByDir("Course");
			}
		}).start();
	}

	private void setupView() {
		if (getFragmentManager().findFragmentById(R.id.fragment_content) == null) {
			switchFragment(new CourseFragment());
		}

		btn_refurbish = (Button) findViewById(R.id.btn_refurbish);
		mainTitle = (TextView) findViewById(R.id.top_bar_title);
		informationBar = (RelativeLayout) findViewById(R.id.top_bar);

		// 个人信息
		userLoad = (RelativeLayout) findViewById(R.id.userr_load_nformation);
		RoundImageView imageButton = (RoundImageView) findViewById(R.id.load);
		userName = (TextView) findViewById(R.id.userName);
		// 个人信息头像设置
		VolleySingleton.getInstance().loadImage(imageButton, UserService.getUserImageUrl());

		userName.setText(UserService.getUserName());
		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btn_refurbish.setVisibility(View.GONE);
				informationBar.setVisibility(View.VISIBLE);
				Drawable btnDrawable = getResources().getDrawable(R.drawable.bg_menu_login_pressed);
				userLoad.setBackgroundDrawable(btnDrawable);
				mainTitle.setText("个人信息");
				YunKeTangBtn.setBackgroundResource(R.drawable.btn_home_normal);
				cloudDiskBtn.setBackgroundResource(R.drawable.btn_cloud_normal);
				settingsBtn.setBackgroundResource(R.drawable.btn_set_normal);
				switchFragment(new UserInformationFragment());
			}
		});

		// 云课堂
		YunKeTangBtn = (Button) findViewById(R.id.btn_home);
		YunKeTangBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				informationBar.setVisibility(View.VISIBLE);
				mainTitle.setText("课程选择");
				btn_refurbish.setVisibility(View.VISIBLE);
				Drawable btnDrawable = getResources().getDrawable(R.drawable.bg_home_user_avatar);
				userLoad.setBackgroundDrawable(btnDrawable);
				YunKeTangBtn.setBackgroundResource(R.drawable.btn_home_selected);
				cloudDiskBtn.setBackgroundResource(R.drawable.btn_cloud_normal);
				settingsBtn.setBackgroundResource(R.drawable.btn_set_normal);
				switchFragment(new CourseFragment());
			}
		});

		// 云盘
		cloudDiskBtn = (Button) findViewById(R.id.btn_cloud);
		cloudDiskBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btn_refurbish.setVisibility(View.VISIBLE);
				informationBar.setVisibility(View.GONE);
				Drawable btnDrawable = getResources().getDrawable(R.drawable.bg_home_user_avatar);
				userLoad.setBackgroundDrawable(btnDrawable);
				cloudDiskBtn.setBackgroundResource(R.drawable.btn_cloud_selected);
				YunKeTangBtn.setBackgroundResource(R.drawable.btn_home_normal);
				settingsBtn.setBackgroundResource(R.drawable.btn_set_normal);
				switchFragment(new SmartPanFragment());
			}
		});

		// 设置
		settingsBtn = (Button) findViewById(R.id.btn_set);
		settingsBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				informationBar.setVisibility(View.VISIBLE);
				mainTitle.setVisibility(View.VISIBLE);
				mainTitle.setText("设置");
				btn_refurbish.setVisibility(View.GONE);
				Drawable btnDrawable = getResources().getDrawable(R.drawable.bg_home_user_avatar);
				userLoad.setBackgroundDrawable(btnDrawable);
				settingsBtn.setBackgroundResource(R.drawable.btn_set_selected);
				YunKeTangBtn.setBackgroundResource(R.drawable.btn_home_normal);
				cloudDiskBtn.setBackgroundResource(R.drawable.btn_cloud_normal);
				switchFragment(new SettingsFragment());
			}
		});
	}
}
